import {shaderMaterial, useTexture} from '@react-three/drei'
import {extend, useFrame} from '@react-three/fiber'
import vertexShader from '../assets/shaders/vertex/fading_image.glsl?raw'
import fragmentShader from '../assets/shaders/fragment/fading_image.glsl?raw'
import {useRef, useState} from 'react'
import {easing} from 'maath'

export const ImageFadeMaterial = shaderMaterial(
  {
    effectFactor: 1.2,
    dispFactor: 0,
    tex: undefined,
    tex2: undefined,
  },
  vertexShader,
  fragmentShader
)

extend({
  ImageFadeMaterial,
})

export const FadingImage = (props) => {
  const ref = useRef()
  const [texture1, texture2, dispTexture] = useTexture([
    '/textures/mei.jpg',
    '/textures/mei2.jpg',
  ])
  const [hovered, setHover] = useState(false)
  useFrame((_state, delta) => {
    // ref.current.dispFactor = THREE.MathUtils.lerp(ref.current.dispFactor, hovered ? 1 : 0, 0.075)
    easing.damp(ref.current, 'dispFactor', hovered ? 1 : 0, 0.4, delta)
  })
  return (
    <mesh
      {...props}
      onPointerOver={(e) => setHover(true)}
      onPointerOut={(e) => setHover(false)}
    >
      <roundedPlaneGeometry
        args={[2.25, 4]} // 16:9
      />
      <imageFadeMaterial
        ref={ref}
        tex={texture1}
        tex2={texture2}
        toneMapped={false}
      />
    </mesh>
  )
}
